package com.java.controller;

import com.java.bean.User;
import com.java.contant.SSMContant;
import com.java.service.UserService;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {
    private final String CODE = "USERCODE";
    private final String REFISTER_PAGE = "user/register";
    private final String LOGIN_PAGE = "user/login";

    @Autowired
    private UserService userService;
    @Value("${apikey}")
    private String apikey;

    //发送手机短信        http://localhost/user/sendsms
    @RequestMapping("/sendsms")
    public String sendSms(@RequestParam String phone, HttpSession session) {
        // 获取6位数验证码
        String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
        System.out.println(code);
        // 将正确的验证码放到session中
        session.setAttribute(CODE, code);
        //初始化clnt,使用单例方式
        YunpianClient clnt = new YunpianClient(apikey).init();
        //发送短信API
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, phone);
        param.put(YunpianClient.TEXT, "【云片网】您的验证码是" + code);
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
        return "ok";
    }

    //异步校检用户名http://localhost/user/checkusername
    //接收json数据
    @RequestMapping("/checkusername")
    @ResponseBody
    public Map<String, Object> checkUsername(@RequestBody User user) {
        //1.获取用户名
        String username = user.getUsername();
        //2.调用service层
        Integer integer = userService.checkUsername(username);
        // System.out.println(user);
        //3.返回json
        Map<String, Object> result = new HashMap<>();
        result.put("data", integer);
        return result;
    }

    //跳转注册页面  method = RequestMethod.POST
    @RequestMapping(value = "/register")
    public String register(@Valid User user, BindingResult bindingResult,
                           String registerCode, HttpSession session) {
        //判断参数
        if (StringUtils.isEmpty(registerCode) || bindingResult.hasErrors()) {
            //参数不合法
            return REFISTER_PAGE;
        }
        //2.判断验证码是否正确
        String userCode = (String) session.getAttribute(CODE);
        if (registerCode.equals(userCode)) {
            //验证码正确， 开始注册
            Integer count = userService.register(user);
            if (count == 1) {
                //注册成功
                return "redirect:/user/login";
            }
        }
        //转发到注册页面
        return REFISTER_PAGE;
    }

    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session, Model model) {
        //1.判断参数是否合法
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return LOGIN_PAGE;
        }
        //2.参数合法
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute(SSMContant.USER, user);
            return "redirect:/item/list";
        } else {
            model.addAttribute("loginInfo", "用户名或密码错误");
        }
        return LOGIN_PAGE;

    }

}
